package com.example.controller;

import com.example.service.DataAnalysisService;
import com.example.service.FieldMappingService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
@Slf4j
@RestController
@RequestMapping("/api/analysis")
@CrossOrigin(origins = "*")
public class DataAnalysisController {

    @Autowired
    private DataAnalysisService dataAnalysisService;


    private FieldMappingService fieldMappingService;

    /**
     * 第一次相关性分析 - 支持算法选择
     * @param algorithm 算法类型：anova 或 correlation
     */
    @PostMapping("/first-correlation")
    public ResponseEntity<Map<String, Object>> firstCorrelationAnalysis(
            @RequestParam(defaultValue = "correlation") String algorithm) {
        try {
            Map<String, Object> result = dataAnalysisService.performFirstCorrelationAnalysis(algorithm);

            // 防护性检查，确保不会传入 null 值给 Map.of()
            if (result == null) {
                throw new RuntimeException("分析服务返回空结果");
            }

            return ResponseEntity.ok(result);

        } catch (Exception e) {
            log.error("第一次相关性分析失败: {}", e.getMessage(), e);

            // 使用 HashMap 来避免 Map.of() 的 null 值限制
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("status", "error");
            errorResponse.put("message", e.getMessage() != null ? e.getMessage() : "未知错误");
            errorResponse.put("timestamp", System.currentTimeMillis());

            return ResponseEntity.badRequest().body(errorResponse);
        }
    }


    /**
     * 第二次相关性分析 - 支持算法选择
     * @param algorithm 算法类型：anova 或 correlation
     */
    @PostMapping("/second-correlation")
    public ResponseEntity<Map<String, Object>> secondCorrelationAnalysis(
            @RequestParam(defaultValue = "correlation") String algorithm) {
        try {
            Map<String, Object> result = dataAnalysisService.performSecondCorrelationAnalysis(algorithm);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("第二次相关性分析失败: {}", e.getMessage(), e);

            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("status", "error");
            errorResponse.put("message", e.getMessage() != null ? e.getMessage() : "未知错误");
            errorResponse.put("timestamp", System.currentTimeMillis());

            return ResponseEntity.badRequest().body(errorResponse);
        }
    }

    /**
     * 数据插补 - 支持算法选择
     * @param algorithm 算法类型：iterative 或 rf（随机森林）
     */
    @PostMapping("/imputation")
    public ResponseEntity<Map<String, Object>> dataImputation(
            @RequestParam(defaultValue = "iterative") String algorithm) {
        try {
            Map<String, Object> result = dataAnalysisService.performDataImputation(algorithm);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("数据插补失败: {}", e.getMessage(), e);

            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("status", "error");
            errorResponse.put("message", e.getMessage() != null ? e.getMessage() : "未知错误");
            errorResponse.put("timestamp", System.currentTimeMillis());

            return ResponseEntity.badRequest().body(errorResponse);
        }
    }


    /**
     * 数据扩充 - 支持算法选择
     * @param algorithm 算法类型：noise 或 smote
     * @param targetSamples 目标样本数，默认5000
     */
    @PostMapping("/augmentation")
    public ResponseEntity<Map<String, Object>> dataAugmentation(
            @RequestParam(defaultValue = "noise") String algorithm,
            @RequestParam(defaultValue = "5000") int targetSamples) {
        try {
            // 构造参数Map
            Map<String, Object> params = new HashMap<>();
            params.put("targetSamples", targetSamples);

            Map<String, Object> result = dataAnalysisService.performDataAugmentation(algorithm, params);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("数据扩充失败", e);
            return ResponseEntity.badRequest().body(Map.of(
                    "status", "error",
                    "message", e.getMessage(),
                    "timestamp", System.currentTimeMillis()
            ));
        }
    }


    /**
     * 获取可用的算法列表
     */
    @GetMapping("/algorithms")
    public ResponseEntity<Map<String, Object>> getAvailableAlgorithms() {
        Map<String, Object> algorithms = Map.of(
                "correlation_algorithms", Map.of(
                        "anova", "方差分析",
                        "correlation", "皮尔逊相关系数"
                ),
                "imputation_algorithms", Map.of(
                        "iterative", "IterativeImputer插补",
                        "rf", "随机森林插补"
                ),
                "augmentation_algorithms", Map.of(
                        "noise", "噪声扩充",
                        "smote", "SMOTE扩充"
                )
        );
        return ResponseEntity.ok(algorithms);
    }

    /**
     * 完整分析流程 - 支持每步算法选择
     */
    @PostMapping("/complete")
    public ResponseEntity<Map<String, Object>> completeAnalysis(
            @RequestParam(defaultValue = "correlation") String firstCorrelationAlg,
            @RequestParam(defaultValue = "correlation") String secondCorrelationAlg,
            @RequestParam(defaultValue = "iterative") String imputationAlg,
            @RequestParam(defaultValue = "noise") String augmentationAlg) {
        try {
            Map<String, Object> result = dataAnalysisService.performCompleteAnalysis(
                    firstCorrelationAlg, secondCorrelationAlg, imputationAlg, augmentationAlg);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Map.of("error", e.getMessage()));
        }
    }


    @GetMapping("/field-mappings")
    public ResponseEntity<Map<String, Object>> getFieldMappings() {
        try {
            Map<String, String> mappings = fieldMappingService.getAllFieldMappings();
            return ResponseEntity.ok(Map.of(
                    "status", "success",
                    "mappings", mappings,
                    "count", mappings.size()
            ));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Map.of(
                    "status", "error",
                    "message", e.getMessage()
            ));
        }
    }

}
